#!/bin/bash

enable_znapzend=false

# data_dir
datadir=/var/openldap/openldap-data

if [ ! -d ${datadir} ]; then
	UUID=$(mdata-get sdc:uuid)
	DDS=zones/${UUID}/data

	if zfs list ${DDS} 1>/dev/null 2>&1; then
		zfs create ${DDS}/openldap-data || true

		zfs set mountpoint=${datadir} ${DDS}/openldap-data

		# znapzend for backup
		znapzendzetup create --recursive --tsformat='%Y-%m-%d-%H%M%S' --donotask \
			SRC '7day=>8hour,30day=>1day,1year=>1week,10year=>1month' ${DDS}
		enable_znapzend=true		
	else
		mkdir -p ${datadir}
	fi
fi

[[ -f ${datadir}/DB_CONFIG ]] || cp /opt/local/share/examples/openldap/DB_CONFIG ${datadir}


chown -R slapd:ldap ${datadir}
chmod 700 ${datadir}
chmod 640 ${datadir}/DB_CONFIG

# conf_dir
confdir=/opt/local/etc/openldap
if [ ! -d ${confdir} ]; then
	UUID=$(mdata-get sdc:uuid)
	DDS=zones/${UUID}/data

	if zfs list ${DDS} 1>/dev/null 2>&1; then
		zfs create ${DDS}/openldap-conf || true

		zfs set mountpoint=${confdir} ${DDS}/openldap-conf

		# znapzend for backup
		znapzendzetup create --recursive --tsformat='%Y-%m-%d-%H%M%S' --donotask \
			SRC '7day=>8hour,30day=>1day,1year=>1week,10year=>1month' ${DDS}
		enable_znapzend=true		
	else
		mkdir -p ${confdir}
	fi
fi

if [ ! -f ${confdir}/slapd.conf ];then
	cp /opt/local/share/examples/openldap/slapd.conf ${confdir}/slapd.conf
	cp /opt/local/share/examples/openldap/slapd.ldif ${confdir}/slapd.ldif
	cp /opt/local/share/examples/openldap/ldap.conf ${confdir}/ldap.conf
	cp -r /opt/local/share/examples/openldap/schema ${confdir}
fi

chown root:ldap ${confdir}/slapd.conf
chmod 640 ${confdir}/slapd.conf

# backup_dir
backupdir=/data/backup
if [ ! -d ${backupdir} ]; then
	UUID=$(mdata-get sdc:uuid)
	DDS=zones/${UUID}/data

	if zfs list ${DDS} 1>/dev/null 2>&1; then
		zfs create ${DDS}/openldap-conf || true

		zfs set mountpoint=${backupdir} ${DDS}/openldap-conf

		# znapzend for backup
		znapzendzetup create --recursive --tsformat='%Y-%m-%d-%H%M%S' --donotask \
			SRC '7day=>8hour,30day=>1day,1year=>1week,10year=>1month' ${DDS}
		enable_znapzend=true		
	else
		mkdir -p ${backupdir}
	fi
fi

if [ ${enable_znapzend} == true ];then
	/usr/sbin/svcadm enable svc:/pkgsrc/znapzend:default
fi